import os
import subprocess


def get_installed_packages():
    result = subprocess.run(['pip', 'freeze'], capture_output=True, text=True)
    return set(result.stdout.splitlines())


def get_required_packages():
    with open('requirement.txt', 'r') as file:
        return set(file.read().splitlines())


def uninstall_unneeded_packages(current_packages, required_packages):
    unneeded_packages = current_packages - required_packages
    for package in unneeded_packages:
        subprocess.run(['pip', 'uninstall', '-y', package])


def install_missing_packages(current_packages, required_packages):
    missing_packages = required_packages - current_packages
    if missing_packages:
        with open('temp_requirements.txt', 'w') as file:
            file.write('\n'.join(missing_packages))
        subprocess.run(['pip', 'install', '-r', 'temp_requirements.txt'])
        os.remove('temp_requirements.txt')


def main():
    current_packages = get_installed_packages()
    required_packages = get_required_packages()

    uninstall_unneeded_packages(current_packages, required_packages)
    install_missing_packages(current_packages, required_packages)


if __name__ == "__main__":
    main()